﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Reflection;
using System.ComponentModel.DataAnnotations.Schema ;
using OpenWeb.Dal.Models;

namespace OpenWeb.Dal.Utils
{
  public class CreateUniqueDbConstraint
  {

    /// <summary>
    /// Metodo per creare un vincolo univico su un campo database tramite
    /// POCO dataAnnnotations
    /// </summary>
    /// <param name="pContext"></param>
    public void CreateUniqueInDbContext(DbContext pContext)
    {
      Type tt ;
      string tablename = "", fieldName = "" ;


      foreach (PropertyInfo pi in typeof(DbContext).GetProperties())
	      {
          if (pi.PropertyType.IsGenericType & pi.PropertyType.Name.Contains("DbSet"))
          {
            tt = pi.PropertyType.GetGenericArguments()[0];
            tablename = tt.GetCustomAttributes(true).OfType<TableAttribute>().FirstOrDefault().Name;

            foreach (var item in tt.GetProperties())
            {
              if (item.GetCustomAttributes(true).OfType<UniqueAttribute>().Any()) 
              {
                fieldName = item.Name;
                pContext.Database.ExecuteSqlCommand("ALTER TABLE " + tablename + " ADD CONSTRAINT con_Unique_" +
                  tablename + "_" + fieldName + "     UNIQUE (" + fieldName + ")");
              }
            }

          }

	      }

      
    }//fM


  }
}
